package com.sgb.kjwl.viewmodel.self.publish;

import androidx.databinding.ObservableField;

import com.google.gson.Gson;
import com.swgk.core.util.MToast;
import com.swgk.core.view.entity.GoodsServicesEntity;
import com.sgb.kjwl.model.entity.user.GetSkuEntity1;
import com.swgk.core.base.api.ICallBack;
import com.sgb.kjwl.api.NewAPIManager;
import com.sgb.kjwl.model.entity.AddLayoutEntity;
import com.sgb.kjwl.model.entity.AlbumEntity;
import com.swgk.core.view.entity.AliProofEntity;
import com.sgb.kjwl.model.entity.ArrEntity;
import com.swgk.core.view.entity.AttrChildEntity;
import com.sgb.link.entity.BrandEntity;
import com.swgk.core.view.entity.GoodsPublishEntity;
import com.swgk.core.view.entity.MenuEntity;
import com.sgb.kjwl.model.entity.ProListEntity;
import com.sgb.kjwl.model.entity.ProvinceEntity;
import com.sgb.kjwl.model.entity.STArrEntity;
import com.sgb.kjwl.model.entity.STPublishEntity;
import com.sgb.kjwl.model.entity.business.StorageManEntity;
import com.sgb.kjwl.model.entity.user.UnitEntity;
import com.sgb.kjwl.repository.SelfRepertory;
import com.sgb.kjwl.view.ui.activity.self.publish.GoodsPublishActivity;
import com.swgk.core.base.BaseViewModel;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.util.SharedPreferenceUtil;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.RequestBody;


import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class GoodsPublishModel extends BaseViewModel {
    public ObservableField<GoodsPublishEntity> goodsPublishEntity = new ObservableField<>(new GoodsPublishEntity());
    public ObservableField<STPublishEntity> sTPublishEntity = new ObservableField<>(new STPublishEntity());
    private GoodsPublishActivity activity;
    private SelfRepertory repertory;
    private int page = 1;
    private int size = 20;
    public int total;

    public GoodsPublishModel(GoodsPublishActivity activity, SelfRepertory repertory) {
        this.activity = activity;
        this.repertory = repertory;
    }

    //获取是否可以填写规格
    public void getSku(String cid3) {
        DialogHelper.showProgressDialog(activity, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        NewAPIManager.getInstance().getGoodsReleasedAPI().getSku(Long.parseLong(cid3)).enqueue(new ICallBack<BaseEntity<List<GetSkuEntity1>>>() {
            @Override
            public void onSuccess(BaseEntity<List<GetSkuEntity1>> data) {
                activity.isSku(data.getData());
            }
        });
    }

    //获取价格单位
    public void getUnitList(String text) {
        DialogHelper.showProgressDialog(activity, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        NewAPIManager.getInstance().getGoodsReleasedAPI().unitList(text).enqueue(new ICallBack<BaseEntity<List<UnitEntity>>>() {
            @Override
            public void onSuccess(BaseEntity<List<UnitEntity>> data) {
                activity.showUnitPop(data.getData());
            }
        });
    }

    //获取出售地区
    public void getAreaModel() {
        NewAPIManager.getInstance().getCommonAPI().getCurrentArea().enqueue(new ICallBack<BaseEntity<List<ProvinceEntity<List<ProvinceEntity>>>>>() {
            @Override
            public void onSuccess(BaseEntity<List<ProvinceEntity<List<ProvinceEntity>>>> data) {
                activity.showAddressPop(data.getData());
            }
        });
    }

    //上传多图片
    public void uploadMutiFileModel(File file, int type, int completeNum) {
        Map<String, RequestBody> photos = new HashMap<>();
        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        photos.put("file" + "\"; filename=\"" + completeNum + "image.jpg", requestBody);
        DialogHelper.showProgressDialog(activity, null, "图片上传中" + completeNum + "/" + activity.imgTotal + "...", 0, false, null).setCanceledOnTouchOutside(false);
        NewAPIManager.getInstance().getNewUploadAPI().uploadFile(photos).enqueue(new ICallBack<BaseEntity>() {
            @Override
            public void onSuccess(BaseEntity data) {
                activity.uploadRefresh(data.getData().toString(), type);
            }
        });
    }

    //上传多图片
    public void listAdapterUp(File file, int type, int completeNum, int position) {
        Map<String, RequestBody> photos = new HashMap<>();
        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        photos.put("file" + "\"; filename=\"" + completeNum + "image.jpg", requestBody);
        DialogHelper.showProgressDialog(activity, null, "图片上传中" + completeNum + "/" + activity.imgTotal + "...", 0, false, null).setCanceledOnTouchOutside(false);
        NewAPIManager.getInstance().getNewUploadAPI().uploadFile(photos).enqueue(new ICallBack<BaseEntity>() {
            @Override
            public void onSuccess(BaseEntity data) {
                activity.listAdapterRefresh(data.getData().toString(), type, position);
            }
        });
    }

    //上传多图片
    public void uploadGoodsImg(List<File> fileList, int type, int completeNum) {
        if (null == fileList || fileList.size() <= 0) {
            return;
        }
        Map<String, RequestBody> photos = new HashMap<>();
        for (int i = 1; i <= fileList.size(); i++) {
            RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), fileList.get(i - 1));
            photos.put("img" + "\"; filename=\"" + i + "image.jpg", requestBody);
        }
        DialogHelper.showProgressDialog(activity, null, "图片上传中" + completeNum + "/" + activity.imgTotal + "...", 0, false, null).setCanceledOnTouchOutside(false);
        NewAPIManager.getInstance().getNewUploadAPI().uploadFileV1(photos).enqueue(new ICallBack<BaseEntity<List<String>>>() {
            @Override
            public void onSuccess(BaseEntity<List<String>> data) {
                activity.uploadImgSuccess(data.getData(), type);
            }
        });
    }

    //仓储列表
    public void getStorageList(String input, boolean isLodMore) {
        page = isLodMore ? page + 1 : 1;
        DialogHelper.showProgressDialog(activity, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        NewAPIManager.getInstance().getGoodsReleasedAPI().getStorageList(page, size, input).enqueue(new ICallBack<BaseEntity<ProListEntity<List<StorageManEntity>>>>() {

            @Override
            public void onSuccess(BaseEntity<ProListEntity<List<StorageManEntity>>> response) {
                activity.showStoragePop(response.getData().getList(), isLodMore);
            }
        });
    }

    //品牌列表
    public void getBrandList(String id, String input) {
        String companyId = SharedPreferenceUtil.getInstance().getSaveStringData(com.swgk.core.util.SharedPreferenceUtil.REAL_ID, "");
        DialogHelper.showProgressDialog(activity, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        NewAPIManager.getInstance().getGoodsReleasedAPI().brandList(id, input).enqueue(new ICallBack<BaseEntity<List<BrandEntity>>>() {

            @Override
            public void onSuccess(BaseEntity<List<BrandEntity>> response) {
                activity.showBrandPop(response.getData());
            }
        });
    }

    //获取属性
    public void getMaterChoose(String id) {
        DialogHelper.showProgressDialog(activity, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        NewAPIManager.getInstance().getGoodsReleasedAPI().getMaterChoose(id, repertory.getAreaCode()).enqueue(new ICallBack<BaseEntity<List<ArrEntity>>>() {
            @Override
            public void onSuccess(BaseEntity<List<ArrEntity>> data) {
                activity.setArrList(data.getData());
            }
        });
    }

    //获取商品分类
    public void getGoodsCategory() {
        DialogHelper.showProgressDialog(activity, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        NewAPIManager.getInstance().getGoodsReleasedAPI().goodsCategory().enqueue(new ICallBack<BaseEntity<List<MenuEntity<MenuEntity<MenuEntity>>>>>() {
            @Override
            public void onSuccess(BaseEntity<List<MenuEntity<MenuEntity<MenuEntity>>>> data) {
                activity.showGoodsTypePop(data.getData());
            }
        });
    }


    //获取商品服务配置
    public void getServiceCategory(String cid) {
        NewAPIManager.getInstance().getGoodsReleasedAPI().goodsService(cid).enqueue(new ICallBack<BaseEntity<List<GoodsServicesEntity>>>() {
            @Override
            public void onSuccess(BaseEntity<List<GoodsServicesEntity>> data) {
                activity.showServices(data.getData());
            }
        });
    }

    /**
     * 获取商品发布
     */
    public void goodsPublish() {
        //移除非必填没有选择属性得选项
        GoodsPublishEntity entity = goodsPublishEntity.get();
        if (entity.getAttrList() != null) {
            ListIterator<AttrChildEntity> iterator = entity.getAttrList().listIterator();
            while (iterator.hasNext()) {
                AttrChildEntity childEntity = iterator.next();
                if (childEntity.getAttrValue() == null || childEntity.getAttrValueId() == null) {
                    iterator.remove();
                }
            }
        }
        String info = new Gson().toJson(goodsPublishEntity.get());
        DialogHelper.showProgressDialog2(activity, null, "数据加载中...", 0, false, null, false);
        NewAPIManager.getInstance().getGoodsReleasedAPI().goodsPublish(goodsPublishEntity.get()).enqueue(new Callback<BaseEntity<Object>>() {
            @Override
            public void onResponse(@NotNull Call<BaseEntity<Object>> call, @NotNull Response<BaseEntity<Object>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) {
                    return;
                }
                if ("ok".equals(response.body().getState())) {
                    activity.showSuccess();
                } else if(response.body().getErrCode().equals("53999")){
                    MToast.showLongToast(activity,"销售价不能低于会员价");
                }else {
                    activity.isError(response.body().getMsg());
                }

            }

            @Override
            public void onFailure(Call<BaseEntity<Object>> call, Throwable t) {
                activity.isError("");
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    //获取上传凭证
    public void getVideoParams() {
        DialogHelper.showProgressDialog(activity, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        NewAPIManager.getInstance().getGoodsReleasedAPI().getVideoParams().enqueue(new ICallBack<BaseEntity<AliProofEntity>>() {
            @Override
            public void onSuccess(BaseEntity<AliProofEntity> data) {
                activity.setAliInfo(data.getData());
            }
        });
    }

    public void getNewGoodsById(String id) {
        DialogHelper.showProgressDialog(activity, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        NewAPIManager.getInstance().getGoodsReleasedAPI().getNewGoodsById(id).enqueue(new ICallBack<BaseEntity<GoodsPublishEntity>>() {
            @Override
            public void onSuccess(BaseEntity<GoodsPublishEntity> data) {
                goodsPublishEntity.set(data.getData());
                activity.setData();
            }
        });
    }

    //获取强度等级
    public void concreteAttrs(int type) {
        DialogHelper.showProgressDialog(activity, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        NewAPIManager.getInstance().getGoodsReleasedAPI().concreteAttrs().enqueue(new ICallBack<BaseEntity<List<STArrEntity>>>() {
            @Override
            public void onSuccess(BaseEntity<List<STArrEntity>> data) {
                if (type == 0) {
                    activity.setStrength(data.getData());
                } else {
                    activity.setStrength2(data.getData());
                }
            }
        });
    }

    /**
     * 商砼发布
     */
    public void concretePublish() {
        String info = new Gson().toJson(sTPublishEntity.get());
        DialogHelper.showProgressDialog(activity, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        NewAPIManager.getInstance().getGoodsReleasedAPI().concretePublish(sTPublishEntity.get()).enqueue(new Callback<BaseEntity>() {
            @Override
            public void onResponse(@NotNull Call<BaseEntity> call, @NotNull Response<BaseEntity> response) {
                if (response.body() == null) {
                    return;
                }
                if ("ok".equals(response.body().getState())) {
                    activity.showSuccess();
                } else {
                    activity.isError(response.body().getMsg());
                }
                DialogHelper.dismissProgressDialog();
            }

            @Override
            public void onFailure(@NotNull Call<BaseEntity> call, @NotNull Throwable t) {
                activity.isError("");
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    //商砼发布详情
    public void concretePublishDetail(String id) {
        DialogHelper.showProgressDialog(activity, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        NewAPIManager.getInstance().getGoodsReleasedAPI().concretePublishDetail(id).enqueue(new ICallBack<BaseEntity<STPublishEntity>>() {
            @Override
            public void onSuccess(BaseEntity<STPublishEntity> data) {
                sTPublishEntity.set(data.getData());
                activity.setStData();
            }
        });
    }

    //获取相册//2021/1/18 更改为用cid3作为请求参数
    public void getSupplierAlbumByCName(String cid) {
        DialogHelper.showProgressDialog(activity, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        NewAPIManager.getInstance().getGoodsReleasedAPI().getSupplierAlbumByCName(cid).enqueue(new ICallBack<BaseEntity<List<AlbumEntity>>>() {
            @Override
            public void onSuccess(BaseEntity<List<AlbumEntity>> data) {
                activity.setAlbum(data.getData());
            }
        });
    }

    public void getAddLayout(String cid) {
        DialogHelper.showProgressDialog(activity, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        NewAPIManager.getInstance().getGoodsReleasedAPI().getAddLayout(cid).enqueue(new ICallBack<BaseEntity<List<AddLayoutEntity<List<AddLayoutEntity>>>>>() {
            @Override
            public void onSuccess(BaseEntity<List<AddLayoutEntity<List<AddLayoutEntity>>>> data) {
                activity.addMoveLayout(data.getData());
            }
        });
    }


    public void getGoodsOtherInfo(String id) {
        DialogHelper.showProgressDialog(activity, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        NewAPIManager.getInstance().getGoodsReleasedAPI().getGoodsOtherInfo(id).enqueue(new ICallBack<BaseEntity<List<AddLayoutEntity<List<AddLayoutEntity>>>>>() {
            @Override
            public void onSuccess(BaseEntity<List<AddLayoutEntity<List<AddLayoutEntity>>>> data) {
                activity.addMoveLayout(data.getData());
            }
        });
    }

    public void getStOtherInfo(String id) {
        DialogHelper.showProgressDialog(activity, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        NewAPIManager.getInstance().getGoodsReleasedAPI().getStOtherInfo(id).enqueue(new ICallBack<BaseEntity<List<AddLayoutEntity<List<AddLayoutEntity>>>>>() {
            @Override
            public void onSuccess(BaseEntity<List<AddLayoutEntity<List<AddLayoutEntity>>>> data) {
                activity.addMoveLayout(data.getData());
            }
        });
    }

    public String getNo() {
        return repertory.getNo();
    }
}
